package com.hermes.biz.search.index;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.wltea.analyzer.lucene.IKAnalyzer;
import com.hermes.biz.search.conn.SQLConnection;

public class IndexManager {
	private static Connection conn = null;
	private int maxBufferedDocs = 500;
	private String indexDir = null;
	private static Logger log = Logger.getLogger(IndexManager.class);
	//private static String itemSearchDir;
	/**
	 * create index
	 * @throws Exception 
	 */
	public boolean createIndexForItems(String sqlStr,String indexDir) throws Exception{
		ResultSet rs = null;
		Statement stmt = null;
		String itemSearchDir = null;
		if(indexDir!=null&&indexDir!=""){
			itemSearchDir = indexDir;
			this.indexDir = indexDir;
    	}
        SQLConnection connection = new SQLConnection();
        conn = connection.getConnction();
        if(conn == null) {

            throw new Exception("not connected");     

        }
        String sql = sqlStr;     
        try {     
            stmt = conn.createStatement();     
            rs = stmt.executeQuery(sql);  
            this.createIndexItemSQL2Doc(rs,itemSearchDir);
            //this.createIndex(rs);   //不要每次重新建立索引，必要时在索引上添加
           
        } catch(Exception e) {
            e.printStackTrace();
            throw new Exception("��ݿ��ѯsql��? sql : " + sql);     
        } finally {
            if(rs != null) rs.close();     
            if(stmt != null) stmt.close();
            if(conn != null) conn.close();
        }
		return false; 
		
	}
	public void createIndexItemSQL2Doc(ResultSet rs,String itemSearchDir) throws CorruptIndexException, LockObtainFailedException, IOException, SQLException{
		Directory directory = null;
		IndexWriter indexWriter = null;
		Analyzer analyzer = null;
		File indexFile = new File(itemSearchDir);
		if(!indexFile.exists()){
			indexFile.mkdir();
		}
		try {
			directory = FSDirectory.open(indexFile);
			analyzer = new IKAnalyzer();
		} catch (IOException e) {			
			e.printStackTrace();
		}
		indexWriter = new IndexWriter(directory,analyzer,true,IndexWriter.MaxFieldLength.UNLIMITED);
		indexWriter.setMaxBufferedDocs(maxBufferedDocs);
		Document doc = null;
		Field item_id = null;
		Field item_title = null;
		Field tag_id = null;
		Field picture_url = null;
		Field description = null;
		
		while(rs.next()) {     
			try{
				doc = new Document();     
				item_id = new Field("item_id", String.valueOf(rs.getInt("item_id")), Field.Store.YES, Field.Index.NOT_ANALYZED, TermVector.NO);
				item_title = new Field("item_title", rs.getString("item_title"), Field.Store.YES, Field.Index.ANALYZED, TermVector.NO);
				tag_id = new Field("tag_id", String.valueOf(rs.getInt("tag_id")), Field.Store.YES, Field.Index.NOT_ANALYZED, TermVector.NO);
				picture_url = new Field("picture_url",rs.getString("picture_url"), Field.Store.YES, Field.Index.NOT_ANALYZED, TermVector.NO);
				description = new Field("description",rs.getString("description"), Field.Store.YES, Field.Index.ANALYZED, TermVector.NO);
				doc.add(item_id);     
				doc.add(item_title);
				doc.add(tag_id);
				doc.add(picture_url);
				doc.add(description);
			}catch(Exception e){
				log.error("create lucene index error : itemid :"+item_id.toString()+"   item_title:"+item_title+"  tag_id:"+tag_id+"  picture_url:"+picture_url+"  description:"+description);
			}
            indexWriter.addDocument(doc);     
        } 
		indexWriter.optimize();
		indexWriter.close();
	}
	
	public String getIndexDir() {
		return indexDir;
	}
	public void setIndexDir(String indexDir) {
		this.indexDir = indexDir;
	}
}
